extends CharacterBody2D
class_name Npc

signal npc_in_screen
signal npc_emotion_changed(current_emotion:Emotion)

const Balloon = preload("res://dialogue/balloon.tscn")
const DissolveShader = preload("uid://chwuwneagkr2n")

## 情绪
enum Emotion{
	CALM, ## 平静
	DEPRESSED, ## 抑郁
	MANIA, ## 躁狂
	HOPE, ## 希望
}

@export var npc_id: String
@export var dialogue_resource: DialogueResource
@export var dialogue_start: String = "start"
@export var sprite_frames: SpriteFrames
@export var start_animation: StringName = "idle"
@export var custom_scale: Vector2
@export var current_emotion:Emotion
@export var max_talk: int
@export var is_once: bool


@onready var body: Node2D = $Body
@onready var animated_sprite_2d: AnimatedSprite2D = $Body/AnimatedSprite2D

var current_count: int = 0



func _ready() -> void:
	animated_sprite_2d.scale = custom_scale
	animated_sprite_2d.sprite_frames = sprite_frames
	animated_sprite_2d.play(start_animation)
	#animated_sprite_2d.material = DissolveShader.duplicate(true)
	DialogHandler.dialogue_end.connect(on_dialogue_end)

func action() -> void :
	var balloon: Node = Balloon.instantiate()
	DialogHandler.current_npc = self
	if get_tree().current_scene != null:
		get_tree().current_scene.add_child(balloon)
		balloon.start(dialogue_resource, dialogue_start)

func change_animate(ani_name:String) -> void:
	animated_sprite_2d.play(ani_name)
	if ani_name in ["up_head","down_head"]:
		await animated_sprite_2d.animation_finished

func _physics_process(delta: float) -> void:
	velocity += get_gravity() * delta
	if is_on_floor():
		velocity = Vector2.ZERO

func set_heading() -> void :
	if Global.player != null:
		var direction : = (Global.player.global_position - global_position).normalized()
		if direction.x < 0:
			body.scale.x = custom_scale.x
		elif direction.x > 0:
			body.scale.x = - custom_scale.x

func change_emotion(emo: Emotion) -> void:
	current_emotion = emo
	npc_emotion_changed.emit(emo)

func on_dialogue_end(cur_id: String) -> void:
	if cur_id == npc_id && is_once:
		exit()
	current_count += 1
	if current_count == max_talk:
		exit()

func on_save_game(saves_data:Array[SavedData]) -> void:
	var save_data = SavedData.new()
	save_data.id = npc_id
	save_data.current_count = current_count
	saves_data.append(save_data)

func _exit_tree() -> void:
	remove_from_group("npc")

func on_load_game(save_data:SavedData) -> void:
	current_count = save_data.current_count
	DialogHandler.current_stage.delete_dialogue_area(current_count)

func exit() -> void:
	var tween = create_tween()
	#tween.tween_property(animated_sprite_2d.material, "shader_parameter/progress", 1.4,0.3).from(-1.3)\
	#.set_ease(Tween.EASE_IN_OUT).set_trans(Tween.TRANS_CUBIC)
	tween.tween_property(self,"modulate:a",0,.3).set_ease(Tween.EASE_IN_OUT).set_trans(Tween.TRANS_CUBIC)
	tween.tween_callback(queue_free)
